﻿using AutoMapper;
using MyToDo.Content;
using MyToDo.Content.UnitOfWork;
using MyToDo.Dtos;
using MyToDo.Extensions;

namespace MyToDo.Service
{
    public class LoginService : ILoginService
    {
        private readonly IUnitOfWork work;
        private readonly IMapper mapper;

        public LoginService(IUnitOfWork work,IMapper mapper)
        {
            this.work = work;
            this.mapper = mapper;
        }

        public async Task<ApiResponse> LoginAsync(string account, string password)
        {
            try
            {
                password = password.GetMD5();
                var model = await work.GetRepository<User>().GetFirstOrDefaultAsync(predicate: x => (x.Account.Equals(account)) && (x.PassWord.Equals(password)));
                if (model == null) return new ApiResponse("账号或密码错误，请重试!");
                return new ApiResponse(true, model);
            }
            catch (Exception ex) 
            {
                return new ApiResponse(false,ex);
            }

        }

        public async Task<ApiResponse> Register(UserDto user)
        {
            try
            {
                var model= mapper.Map<User>(user);
                var repository= work.GetRepository<User>();
                var userModel = await repository.GetFirstOrDefaultAsync(predicate: x =>x.Account.Equals(model.Account));
                if (userModel != null) return new ApiResponse($"当前账号{model}已被注册");
                model.CreatDate = DateTime.Now;
                model.PassWord = model.PassWord.GetMD5();
                await repository.InsertAsync(model);
                if (await work.SaveChangesAsync() > 0) return new ApiResponse(true,model);
                return new ApiResponse("注册用户失败");         
            }
            catch (Exception)
            {
                return new ApiResponse("注册用户失败");
            }
        }
    }
}
